package com.ycsj.goldmedalnewconcept.teacher.activity;


import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.blankj.utilcode.util.ToastUtils;
import com.ycsj.common.base.BaseActivity;
import com.ycsj.common.base.BaseApplication;
import com.ycsj.common.base.BusInfo;
import com.ycsj.common.manager.BqaManager;
import com.ycsj.common.utils.GsonUtil;
import com.ycsj.common.utils.ScreenUtils;
import com.ycsj.common.utils.UiUtils;
import com.ycsj.common.view.scroll.MyGridView;
import com.ycsj.goldmedalnewconcept.R;
import com.ycsj.goldmedalnewconcept.common.HttpAddress;
import com.ycsj.goldmedalnewconcept.common.adapter.UnitGvAdapter;
import com.ycsj.goldmedalnewconcept.common.bean.UnitGvInfo;
import com.ycsj.goldmedalnewconcept.common.http.HttpCallBack;
import com.ycsj.goldmedalnewconcept.common.http.HttpUtils;
import com.ycsj.goldmedalnewconcept.common.util.AccountUtils;
import com.ycsj.goldmedalnewconcept.common.util.LayoutUtils;
import com.ycsj.goldmedalnewconcept.common.util.LpUtils;
import com.ycsj.goldmedalnewconcept.master.bean.ListBean;
import com.ycsj.goldmedalnewconcept.master.bean.LookInfo;
import com.ycsj.goldmedalnewconcept.teacher.bean.ClassInfo;
import com.ycsj.goldmedalnewconcept.teacher.utils.ClassPoputil;
import com.ycsj.goldmedalnewconcept.view.MyScrollView;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import okhttp3.Call;

/**
 * 教师端教学与反思--单元选择界面
 * Created by Administrator on 2019/5/7 0007.
 */

public class TeacherChooseUnitActivity extends BaseActivity {

    @BindView(R.id.rl_content)
    RelativeLayout rlContent;
    @BindView(R.id.rl_loading)
    RelativeLayout rlLoading;
    @BindView(R.id.lv_edit)
    ImageView lvEdit;
    @BindView(R.id.ll_title)
    LinearLayout llTitle;
    @BindView(R.id.scrollview)
    MyScrollView scrollView;
    @BindView(R.id.rl_contain)
    RelativeLayout rlContain;
    @BindView(R.id.iv_back)
    ImageView ivBack;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.mgv)
    MyGridView mgv;

    //背景图的设计宽高
    private int width = 750;
    private int height = 10672;

    private int screenWidth;
    //用于放置所有按钮的线性布局的高度
    private int llheight;

    //每个Unit单元的TextView的大小
    private int itemSize = 48;

    //添加Unit单元的布局参数
    private RelativeLayout.LayoutParams lp;

    //所有班级的列表
    private List<ClassInfo.ListBean> classInfos;

    //记录弹出展示班级列表PopUpWindow的选中位置的值,默认第一个被选中
    private int popSelectedPos = 0;


    //创建的的72个单元的数据模型
    private List<ListBean> unitDatas;

    //用于存放所有布局参数
    private List<Integer> paramsMarginlefts;
    private List<Integer> paramsMargintops;

    //展示单元栏目的数据格式
    private List<UnitGvInfo> tabDatas;


    //展示单元选项的GridView适配器
    private UnitGvAdapter gvAdapter;

    //记录点击TextView跳转时候的索引位置
    private int index = -1;

    //更新页面状态的标识
    public static final int UPDATESTATE = 0x770;

    @Override
    protected int getContentLayout() {
        return R.layout.teacher_activity_choose_unit_jxfs;
    }

    @Override
    protected void init() {

        initStateBar();

        //初始化标题
        initTitle();

        //初始化编辑按钮
        initEdit();

        //初始化单元导航栏
        initGv();

        //动态配置滚动布局的宽高
        initParamsBg();

        //初始化72个单元的数据
        init72UnitDatas();

        //请求班级数据
        httpClass();
    }

    /**
     * 初始化标题
     */
    private void initTitle() {
        tvTitle.setText("教学与反思");
    }

    /**
     * 初始化选择班级的按钮
     */
    private void initEdit() {
        RelativeLayout.LayoutParams lp = LpUtils.getRelatLp(UiUtils.dp2px(36), UiUtils.dp2px(36));
        lp.addRule(RelativeLayout.CENTER_IN_PARENT);
        lvEdit.setLayoutParams(lp);
        lvEdit.setImageResource(R.drawable.common_class);
    }

    /**
     * 动态设置背景图的宽高
     */
    private void initParamsBg() {
        screenWidth = ScreenUtils.getScreenWidth(this);
        //计算高度,根据设计图的宽高比来动态配置
        llheight = screenWidth * height / width;
        LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(screenWidth, llheight);
        rlContain.setLayoutParams(lp);
    }

    /**
     * 请求班级数据
     */
    public void httpClass() {

        Map<String, String> map = new HashMap<>();
        map.put("type", "1");
        map.put("ttel", AccountUtils.getAccount(this));
        map.put("platform", "2");

        HttpUtils.post(HttpAddress.GETCLASS, map, this, new HttpUtils.CallBack() {
            @Override
            public void onError(Call call, Exception e, int id) {
                if (null != rlLoading && rlLoading.getVisibility() != View.GONE) {
                    rlLoading.setVisibility(View.GONE);
                }
                ToastUtils.showShort(BaseApplication.ERROR);
            }

            @Override
            public void onResponse(String response, int id) {
                ClassInfo info = null;
                try {
                    info = GsonUtil.jsonToBean(response, ClassInfo.class);
                } catch (Exception e) {
                    Log.i("test", "数据解析异常");
                }

                if (null != info) {
                    if (1 == info.getState()) {
                        //返回成功
                        classInfos = info.getList();
                        if (null != classInfos && classInfos.size() != 0) {
                            //设置
                            lvEdit.setVisibility(View.VISIBLE);

                            //请求页面单元数据
                            httpPageData(BqaManager.NORML);

                        } else {
                            if (null != rlLoading && rlLoading.getVisibility() != View.GONE) {
                                rlLoading.setVisibility(View.GONE);
                            }
                            ToastUtils.showShort("没有班级数据");
                            lvEdit.setVisibility(View.GONE);
                        }

                    } else {
                        //返回错误
                        if (null != rlLoading && rlLoading.getVisibility() != View.GONE) {
                            rlLoading.setVisibility(View.GONE);
                        }
                        ToastUtils.showShort("服务器返回异常,状态码是:" + info.getState());
//                        Log.i("test", "服务器返回异常,状态码是:" + info.getState());
                    }

                } else {
                    Log.i("test", "服务器返回数据为空");
                }
            }
        });
    }

    /**
     * 初始化72个单元的数据
     */
    private void init72UnitDatas() {

        unitDatas = new ArrayList<>();

        //创建72个单元数据
        for (int i = 0; i < 72; i++) {
            ListBean info = new ListBean();
            //对应的72--1单元号
            info.unit = (72 - i) + "";
            info.hasFansi = "0";//默认没有反思
            unitDatas.add(info);
        }
    }


    /**
     * 请求页面数据的方法
     *
     * @param method
     */
    private void httpPageData(final int method) {
        Map<String, String> map = new HashMap<>();
        map.put("type", "22");
        map.put("c", AccountUtils.getAccount(this));
        map.put("role", "2");
        map.put("schoolid", AccountUtils.getSchoolId(this));
        map.put("userclass", classInfos.get(popSelectedPos).getNum() + "");
//        LogUtils.iTag("test", "type=22&c=" + AccountUtils.getAccount(this) + "&role=2&schoolid=" + AccountUtils.getSchoolId(this) + "&userclass=" + classInfos.get(popSelectedPos).getNum() + "");
        HttpUtils.post(HttpAddress.JXBKUNIT, map, this, new HttpCallBack<LookInfo>() {
            @Override
            public void onSuccess(LookInfo info) {
                if (rlLoading.getVisibility() != View.GONE) {
                    rlLoading.setVisibility(View.GONE);
                }

                if (rlContent.getVisibility() != View.VISIBLE) {
                    rlContent.setVisibility(View.VISIBLE);
                }

                //获取数据成功
                if (method == BqaManager.NORML) {

                    //获取有状态的数据
                    List<ListBean> stateDatas = info.list;


                    if (null != stateDatas) {
                        //将有状态的数据复制给自己创建的数据集中

                        for (int i = 0; i < stateDatas.size(); i++) {
                            if (null != getData(stateDatas.get(i).unit)) {
                                ListBean stateBean = stateDatas.get(i);
                                ListBean unitBean = getData(stateDatas.get(i).unit);
                                unitBean.content = stateBean.content;
                                unitBean.hasFansi = "1";
                                unitBean.edit_status = stateBean.edit_status;
                                unitBean.is_null = stateBean.is_null;
                                unitBean.lesson = stateBean.lesson;
                                unitBean.row_id = stateBean.row_id;
                                unitBean.status = stateBean.status;
                            }
                        }
                    }

                    //动态计算每个按钮的布局参数宽和高
                    initPositon();

                    //设置ScrollView的滚动监听事件
                    initScrollListener();

                } else if (method == BqaManager.PULLREFRESH) {

                    //选择班级后更新界面,1将unitDatas清空,2添加72个单元信息,3更新界面72个TextView的背景状态
                    unitDatas.clear();

                    for (int i = 0; i < 72; i++) {
                        ListBean listBean = new ListBean();
                        //对应的72--1单元号
                        listBean.unit = (72 - i) + "";
                        listBean.hasFansi = "0";
                        unitDatas.add(listBean);
                    }

                    //获取有状态的数据
                    List<ListBean> stateDatas = info.list;

                    if (null != stateDatas) {
                        //将有状态的数据复制给自己创建的数据集中
                        for (int i = 0; i < stateDatas.size(); i++) {
                            if (null != getData(stateDatas.get(i).unit)) {
                                ListBean stateBean = stateDatas.get(i);
                                ListBean unitBean = getData(stateDatas.get(i).unit);
                                unitBean.content = stateBean.content;
                                unitBean.hasFansi = "1";
                                unitBean.edit_status = stateBean.edit_status;
                                unitBean.is_null = stateBean.is_null;
                                unitBean.lesson = stateBean.lesson;
                                unitBean.row_id = stateBean.row_id;
                                unitBean.status = stateBean.status;
                            }
                        }
                    }

                    //更新TextView的背景状态
                    int childCount = rlContain.getChildCount();

                    for (int i = 0; i < childCount; i++) {
                        TextView tv = (TextView) rlContain.getChildAt(i);

                        //教师端--教学与反思--单元选择界面只有2种状态,已编辑和未编辑内容
                        if ("1".equals(unitDatas.get(i).hasFansi)) {
                            //有编辑内容
                            tv.setBackgroundResource(R.drawable.haseditcontent);
                        } else {
                            //没有编辑内容
                            tv.setBackgroundResource(R.drawable.tv_unit_open);
                        }
                    }
                }
            }

            @Override
            public void onError(String e) {
                if (rlLoading.getVisibility() != View.GONE) {
                    rlLoading.setVisibility(View.GONE);
                }

                ToastUtils.showShort(BaseApplication.ERROR);
            }
        });
    }


    /**
     * 动态计算72个单元的布局宽和高
     */
    private void initPositon() {

        paramsMarginlefts = LayoutUtils.getMarinLefts(screenWidth);

        paramsMargintops = LayoutUtils.getMarinTops(llheight);

        //动态添加按钮布局
        if (paramsMarginlefts.size() != 0 && paramsMargintops.size() != 0) {

            for (int i = 1; i <= paramsMargintops.size(); i++) {

                TextView tv = (TextView) View.inflate(this, R.layout.unit_item_tv, null);

                lp = new RelativeLayout.LayoutParams(UiUtils.dp2px(itemSize), UiUtils.dp2px(itemSize));
                lp.topMargin = paramsMargintops.get(i - 1);
                lp.leftMargin = paramsMarginlefts.get(i - 1);
                tv.setText((73 - i) + "");

                //给每个TextView添加一个表示
                tv.setTag(i - 1);

                //配置TextView的paddingleft和paddingtop,确保文字居中
                if (i > 63 && i <= paramsMargintops.size()) {
                    //文字为1到9时
                    tv.setPadding(UiUtils.dp2px(15), UiUtils.dp2px(7), 0, 0);
                } else {
                    //文字为两位数数
                    tv.setPadding(UiUtils.dp2px(11), UiUtils.dp2px(7), 0, 0);
                }

                //教师端--教学与反思--单元选择界面只有2种状态,已编辑和未编辑内容
                if ("1".equals(unitDatas.get(i - 1).hasFansi)) {
                    //有编辑内容
                    tv.setBackgroundResource(R.drawable.haseditcontent);
                } else {
                    //没有编辑内容
                    tv.setBackgroundResource(R.drawable.tv_unit_open);
                }

                tv.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        index = (int) view.getTag();
                        //跳转到重难点界面
                        TeacherPrepareLessonsActivity.goActivity(TeacherChooseUnitActivity.this, unitDatas.get(index), classInfos.get(popSelectedPos).getNum() + "");
                    }
                });

                rlContain.addView(tv, lp);
            }
        }
    }


    /**
     * ScrollView的滚动监听事件
     */
    private void initScrollListener() {

        //初次进入的时候让ScrollView滚动到底部
        scrollView.post(new Runnable() {
            @Override
            public void run() {
                scrollView.fullScroll(ScrollView.FOCUS_DOWN);
            }
        });

        //滚动监听
        scrollView.setOnScrollListener(new MyScrollView.OnScrollListener() {
            @Override
            public void onScroll(int scrollY) {
                //判断滚动距离,同步顶部Unit单元的同步状态

                TextView tv53 = (TextView) rlContain.getChildAt(53); //对应19
                int top53Distance = tv53.getTop() - ScreenUtils.getScreenHeight(TeacherChooseUnitActivity.this) + UiUtils.dp2px(80);

                TextView tv35 = (TextView) rlContain.getChildAt(35);//对应3
                int top35Distance = tv35.getTop() - ScreenUtils.getScreenHeight(TeacherChooseUnitActivity.this) + UiUtils.dp2px(80);

                TextView tv17 = (TextView) rlContain.getChildAt(17);//对应3
                int top17Distance = tv17.getTop() - ScreenUtils.getScreenHeight(TeacherChooseUnitActivity.this) + UiUtils.dp2px(80);

                //从下往上滑
                if (scrollY > top53Distance) {
                    //1-1选中
                    sysGvState(0);
                } else if (scrollY > top35Distance) {
                    //1-2选中,滚动距离为9978-5615 对应的是53-35
                    sysGvState(1);
                } else if (scrollY > top17Distance) {
                    //1-3选中,滚动距离为5615-221 对应的是35-17
                    sysGvState(2);
                } else if (scrollY > 0) {
                    //1-4选中
                    sysGvState(3);
                }
            }
        });
    }


    /**
     * 点击事件
     *
     * @param v
     */
    @OnClick({R.id.iv_back, R.id.lv_edit})
    public void clickEvent(View v) {
        switch (v.getId()) {
            case R.id.iv_back:
                //返回
                finish();
                break;
            case R.id.lv_edit:
                //选择班级的弹框
                showClassPop();
                break;
        }
    }


    /**
     * 选择班级的弹框
     */
    private void showClassPop() {
        ClassPoputil.showClassPop(this, classInfos, popSelectedPos, llTitle, new ClassPoputil.onPopItemClickListener() {
            @Override
            public void onItemClick(int pos) {
                //记录当前点击条目的位置
                popSelectedPos = pos;

                //请求页面数据
                httpPageData(BqaManager.PULLREFRESH);
            }
        });
    }

    /**
     * 根据unit返回对象的方法
     */
    public ListBean getData(String unit) {
        ListBean res = null;
        for (int i = 0; i < unitDatas.size(); i++) {
            if (unit.equals(unitDatas.get(i).unit)) {
                res = unitDatas.get(i);
                break;
            }
        }

        return res;
    }


    /**
     * 初始化单元导航栏
     */
    private void initGv() {

        tabDatas = new ArrayList<>();
        UnitGvInfo oneUnitGvInfo = new UnitGvInfo(R.drawable.one_select, R.drawable.one_unselect, true);
        UnitGvInfo twoUnitGvInfo = new UnitGvInfo(R.drawable.two_select, R.drawable.two_unselect, false);
        UnitGvInfo threeUnitGvInfo = new UnitGvInfo(R.drawable.three_select, R.drawable.three_unselect, false);
        UnitGvInfo fourUnitGvInfo = new UnitGvInfo(R.drawable.four_select, R.drawable.four_unselect, false);
        tabDatas.add(oneUnitGvInfo);
        tabDatas.add(twoUnitGvInfo);
        tabDatas.add(threeUnitGvInfo);
        tabDatas.add(fourUnitGvInfo);

        gvAdapter = new UnitGvAdapter(this, tabDatas, R.layout.item_gv_unit);

        mgv.setAdapter(gvAdapter);

        //条目点击事件
        mgv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {

                //根据点击的条目让ScrollView滚动到指定位置
                switch (position) {
                    case 0:
                        //滚动到底部
                        scrollView.fullScroll(ScrollView.FOCUS_DOWN);
                        break;
                    case 1://顶部停留在19单元
                        scrollView.post(new Runnable() {
                            @Override
                            public void run() {
                                TextView tv = (TextView) rlContain.getChildAt(53);
                                scrollView.smoothScrollTo(0, tv.getTop() - ScreenUtils.getScreenHeight(TeacherChooseUnitActivity.this) + UiUtils.dp2px(80));
                            }
                        });
                        break;
                    case 2://37
                        scrollView.post(new Runnable() {
                            @Override
                            public void run() {
                                TextView tv = (TextView) rlContain.getChildAt(35);
                                RelativeLayout.LayoutParams lp = (RelativeLayout.LayoutParams) tv.getLayoutParams();
                                scrollView.smoothScrollTo(0, tv.getTop() - ScreenUtils.getScreenHeight(TeacherChooseUnitActivity.this) + UiUtils.dp2px(80));
                            }
                        });
                        break;
                    case 3:
                        //滚动到顶部
                        scrollView.fullScroll(ScrollView.FOCUS_UP);
                        break;
                }

                if (tabDatas.get(position).isSelected) {
                    return;
                } else {
                    sysGvState(position);
                }
            }
        });
    }

    /**
     * @param pos
     */
    private void sysGvState(int pos) {
        for (int i = 0; i < tabDatas.size(); i++) {
            if (i == pos) {
                tabDatas.get(i).isSelected = true;
            } else {
                tabDatas.get(i).isSelected = false;
            }
        }
        gvAdapter.notifyDataSetChanged();
    }

    /**
     * 事件处理
     *
     * @param busInfo
     */
    @Override
    public void busEvent(BusInfo busInfo) {
        super.busEvent(busInfo);
        if (null != busInfo && UPDATESTATE == busInfo.type) {
            //当老师发布新反思时更新状态
//            TextView tv = (TextView) rlContain.getChildAt(index);
//            tv.setBackgroundResource(R.drawable.haseditcontent);
//            unitDatas.get(index).hasFansi = "1";
//            unitDatas.get(index).content = busInfo.msg;
//            unitDatas.get(index).row_id = busInfo.row_id;

            httpPageData(BqaManager.PULLREFRESH);
        }
    }
}
